// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 获取城市列表并填充下拉选择框
    fetchCities();
    
    // 绑定事件处理程序
    document.getElementById('bus-search-form').addEventListener('submit', searchBusLines);
    document.getElementById('search-start').addEventListener('click', function() {
        searchLocation('start');
    });
    document.getElementById('search-end').addEventListener('click', function() {
        searchLocation('end');
    });
    document.getElementById('transfer-form').addEventListener('submit', planRoute);
    
    // 城市选择输入框事件绑定
    document.getElementById('bus-city-input').addEventListener('input', handleCityInput);
    document.getElementById('transfer-city-input').addEventListener('input', handleCityInput);
});

// 存储所有城市数据的全局变量
let allCities = [];

/**
 * 获取城市列表
 */
function fetchCities() {
    showLoading('正在加载城市列表...');
    
    fetch('/api/cities')
        .then(response => response.json())
        .then(data => {
            hideLoading();
            
            if (data.return_code === 'ok') {
                const cities = data.returl_list || [];
                allCities = cities; // 保存到全局变量
                populateCityDatalist(cities);
            } else {
                showError('获取城市列表失败: ' + (data.error_code || '未知错误'));
            }
        })
        .catch(error => {
            hideLoading();
            showError('获取城市列表失败: ' + error.message);
        });
}

/**
 * 处理城市输入框的输入事件
 */
function handleCityInput(event) {
    const input = event.target;
    const inputValue = input.value.trim().toLowerCase();
    const inputId = input.id;
    
    // 确定相应的城市ID隐藏字段
    const cityIdField = inputId === 'bus-city-input' ? 
        document.getElementById('bus-city-id') : 
        document.getElementById('transfer-city-id');
    
    // 当用户选择了datalist中的某个选项时
    const selectedCity = allCities.find(city => {
        const cityName = decodeUnicode(city.city || city.cityname || "").toLowerCase();
        return cityName === inputValue;
    });
    
    if (selectedCity) {
        cityIdField.value = selectedCity.cityid;
    } else {
        cityIdField.value = '';
    }
}

/**
 * 填充城市datalist
 */
function populateCityDatalist(cities) {
    console.log("收到的城市数据:", cities);
    
    const busCityList = document.getElementById('bus-city-list');
    const transferCityList = document.getElementById('transfer-city-list');
    
    // 清空现有选项
    busCityList.innerHTML = '';
    transferCityList.innerHTML = '';
    
    // 添加城市选项
    cities.forEach(city => {
        // 兼容不同的键名
        const cityName = decodeUnicode(city.city || city.cityname || "未知城市");
        
        const option1 = document.createElement('option');
        option1.value = cityName;
        option1.dataset.cityid = city.cityid;
        busCityList.appendChild(option1);
        
        const option2 = document.createElement('option');
        option2.value = cityName;
        option2.dataset.cityid = city.cityid;
        transferCityList.appendChild(option2);
    });
}

/**
 * 解码Unicode编码的字符串（处理城市名称中的\u编码）
 */
function decodeUnicode(str) {
    if (typeof str !== 'string') {
        return str;
    }
    return str.replace(/\\u([0-9a-fA-F]{4})/g, (match, grp) => {
        return String.fromCharCode(parseInt(grp, 16));
    });
}

/**
 * 搜索公交路线
 */
function searchBusLines(event) {
    event.preventDefault();
    
    const cityId = document.getElementById('bus-city-id').value;
    const keywords = document.getElementById('bus-keywords').value;
    
    if (!cityId || !keywords) {
        showError('请选择城市并输入公交线路');
        return;
    }
    
    showLoading('正在搜索公交路线...');
    
    // 使用新的完整API，同时获取正向和反向路线
    fetch(`/api/bus_lines_complete?city_id=${cityId}&keywords=${encodeURIComponent(keywords)}`)
        .then(response => response.json())
        .then(data => {
            hideLoading();
            
            if (data.return_code === 'ok') {
                const forwardData = data.forward_data || {};
                const reverseData = data.reverse_data || {};
                
                let allLines = [];
                
                // 处理正向路线
                if (forwardData.return_code === 'ok' && forwardData.returl_list && forwardData.returl_list.length > 0) {
                    // 为每条线路添加方向标识
                    const forwardLines = forwardData.returl_list.map(line => {
                        return {
                            ...line, 
                            direction: 'forward'  // 标记为去程方向
                        };
                    });
                    allLines = [...allLines, ...forwardLines];
                }
                
                // 处理反向路线
                if (reverseData.return_code === 'ok' && reverseData.returl_list && reverseData.returl_list.length > 0) {
                    // 添加反向路线，并标记方向
                    const reverseLines = reverseData.returl_list.map(line => {
                        return {
                            ...line,
                            direction: 'reverse',  // 标记为返程方向
                            // 交换起终点站显示
                            original_stastan: line.bus_stastan,
                            original_endstan: line.bus_endstan,
                            bus_stastan: line.bus_endstan,
                            bus_endstan: line.bus_stastan
                        };
                    });
                    allLines = [...allLines, ...reverseLines];
                }
                
                // 显示所有路线
                displayBusLines(allLines, cityId);
            } else {
                showError('搜索公交路线失败: ' + (data.error_code || '未知错误'));
            }
        })
        .catch(error => {
            hideLoading();
            showError('搜索公交路线失败: ' + error.message);
        });
}

/**
 * 显示公交路线搜索结果
 */
function displayBusLines(busLines, cityId) {
    const resultsContainer = document.getElementById('bus-search-results');
    
    if (busLines.length === 0) {
        resultsContainer.innerHTML = '<div class="alert alert-warning">未找到匹配的公交路线</div>';
        return;
    }
    
    let html = '<h4>搜索结果</h4><div class="list-group">';
    
    // 对路线进行排序：先显示正向路线，再显示反向路线
    const sortedLines = [...busLines].sort((a, b) => {
        if (a.direction === b.direction) return 0;
        return a.direction === 'forward' ? -1 : 1;
    });
    
    sortedLines.forEach(line => {
        // 根据方向显示不同的标记
        const directionLabel = line.direction === 'reverse' ? 
            '<span class="badge bg-info">返程</span>' : 
            '<span class="badge bg-primary">去程</span>';
            
        // 查找匹配的反向线路（其实只需要存储other_lineid）
        const otherLineId = line.other_lineid || '';
        
        html += `
            <div class="bus-line-item" data-cityid="${cityId}" 
                 data-linestrid="${line.bus_linestrid}" 
                 data-linenum="${line.bus_linenum}" 
                 data-staname="${line.bus_staname}"
                 data-otherlineid="${otherLineId}"
                 data-direction="${line.direction || 'forward'}">
                <div class="row">
                    <div class="col-md-3">
                        <strong>${line.bus_staname}</strong> 路 ${directionLabel}
                    </div>
                    <div class="col-md-9">
                        ${line.bus_stastan} → ${line.bus_endstan}
                    </div>
                </div>
                <div class="mt-2">
                    <button class="btn btn-sm btn-primary view-realtime">查看实时位置</button>
                    <button class="btn btn-sm btn-outline-primary view-schedule">查看发车时刻表</button>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    resultsContainer.innerHTML = html;
    
    // 绑定事件处理程序
    document.querySelectorAll('.view-realtime').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const item = this.closest('.bus-line-item');
            const cityId = item.dataset.cityid;
            const linestrid = item.dataset.linestrid;
            const linenum = item.dataset.linenum;
            const staname = item.dataset.staname;
            const direction = item.dataset.direction || 'forward';
            const otherLineId = item.dataset.otherlineid || null;
            
            getRealtimeBusLocation(cityId, linestrid, linenum, staname, direction, otherLineId);
            
            // 切换到实时位置选项卡
            document.getElementById('realtime-tab').click();
        });
    });
    
    document.querySelectorAll('.view-schedule').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const item = this.closest('.bus-line-item');
            const cityId = item.dataset.cityid;
            const staname = item.dataset.staname;
            const direction = item.dataset.direction || 'forward';
            
            getBusSchedule(cityId, staname, direction);
        });
    });
}

/**
 * 获取公交实时位置
 */
function getRealtimeBusLocation(cityId, linestrid, linenum, staname, direction = 'forward', otherLineId = null) {
    showLoading('正在获取实时位置...');
    
    fetch(`/api/realtime_location?city_id=${cityId}&bus_linestrid=${encodeURIComponent(linestrid)}&bus_linenum=${encodeURIComponent(linenum)}&bus_staname=${encodeURIComponent(staname)}`)
        .then(response => response.json())
        .then(data => {
            hideLoading();
            
            if (data.return_code === 'ok') {
                // 保存反向路线ID，用于换向按钮
                let reverseLineId = null;
                if (data.returl_list && data.returl_list.lineinfo && data.returl_list.lineinfo.other_lineid) {
                    reverseLineId = data.returl_list.lineinfo.other_lineid;
                }
                
                displayRealtimeLocation(data.returl_list, direction, reverseLineId, cityId, linenum, staname);
            } else {
                showError('获取实时位置失败: ' + (data.error_code || '未知错误'));
            }
        })
        .catch(error => {
            hideLoading();
            showError('获取实时位置失败: ' + error.message);
        });
}

/**
 * 显示公交实时位置
 */
function displayRealtimeLocation(data, direction = 'forward', reverseLineId = null, cityId = null, linenum = null, staname = null) {
    const resultsContainer = document.getElementById('realtime-results');
    
    if (!data || !data.lineinfo) {
        resultsContainer.innerHTML = '<div class="alert alert-warning">无法获取实时位置信息</div>';
        return;
    }
    
    const lineInfo = data.lineinfo;
    const stations = data.stations || [];
    const buses = data.buses || [];
    
    // 显示方向标记
    const directionLabel = direction === 'reverse' ? 
        '<span class="badge bg-info">返程</span>' : 
        '<span class="badge bg-primary">去程</span>';
    
    let html = `
        <div class="card mb-4">
            <div class="card-body">
                <h4>${lineInfo.bus_staname}路 ${directionLabel}</h4>
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>起点站:</strong> ${lineInfo.sta_sta}</p>
                        <p><strong>终点站:</strong> ${lineInfo.end_sta}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>首班车:</strong> ${lineInfo.fir_time}</p>
                        <p><strong>末班车:</strong> ${lineInfo.end_time}</p>
                        <p><strong>票价:</strong> ${lineInfo.bus_money}</p>
                    </div>
                </div>`;
    
    // 添加换向按钮（如果有反向路线ID）
    if (reverseLineId && cityId && linenum && staname) {
        const reverseDirection = direction === 'forward' ? 'reverse' : 'forward';
        const buttonLabel = direction === 'forward' ? '查看返程路线' : '查看去程路线';
        
        html += `
                <div class="mt-3">
                    <button class="btn btn-outline-primary switch-direction" 
                            data-cityid="${cityId}" 
                            data-linestrid="${reverseLineId}" 
                            data-linenum="${linenum}" 
                            data-staname="${staname}" 
                            data-direction="${reverseDirection}">
                        ${buttonLabel}
                    </button>
                </div>`;
    }
    
    html += `
            </div>
        </div>
        
        <h4>站点信息</h4>
    `;
    
    if (stations.length > 0) {
        html += '<ul class="stations-list">';
        
        stations.forEach((station, index) => {
            // 查找是否有公交车在这个站点
            const hasBus = buses.some(bus => {
                return bus.dis_stat === index && bus.distance === 0;
            });
            
            // 查找是否有公交车即将到达这个站点
            const approachingBuses = buses.filter(bus => {
                return bus.dis_stat === index && bus.distance > 0;
            });
            
            let busInfo = '';
            if (hasBus) {
                busInfo = '<span class="badge bg-success">车辆已到站</span>';
            } else if (approachingBuses.length > 0) {
                approachingBuses.forEach(bus => {
                    busInfo += `<span class="badge bg-warning text-dark">车辆距离 ${bus.distance} 米</span> `;
                });
            }
            
            html += `
                <li class="station-item ${hasBus ? 'has-bus' : ''}">
                    <div class="row">
                        <div class="col-9">
                            <span>${station.bus_staname}</span>
                        </div>
                        <div class="col-3">
                            ${busInfo}
                        </div>
                    </div>
                </li>
            `;
        });
        
        html += '</ul>';
    } else {
        html += '<div class="alert alert-info">暂无站点信息</div>';
    }
    
    resultsContainer.innerHTML = html;
    
    // 绑定换向按钮事件
    document.querySelectorAll('.switch-direction').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const cityId = this.dataset.cityid;
            const linestrid = this.dataset.linestrid;
            const linenum = this.dataset.linenum;
            const staname = this.dataset.staname;
            const direction = this.dataset.direction;
            
            getRealtimeBusLocation(cityId, linestrid, linenum, staname, direction);
        });
    });
}

/**
 * 获取公交发车时刻表
 */
function getBusSchedule(cityId, staname, direction = 'forward') {
    showLoading('正在获取发车时刻表...');
    
    // 实际上只有一个API端点
    fetch(`/api/bus_schedule?city_id=${cityId}&bus_staname=${encodeURIComponent(staname)}`)
        .then(response => response.json())
        .then(data => {
            hideLoading();
            
            if (data.return_code === 'ok') {
                displayBusSchedule(data.returl_list, staname, direction);
            } else {
                showError('获取发车时刻表失败: ' + (data.error_code || '未知错误'));
            }
        })
        .catch(error => {
            hideLoading();
            showError('获取发车时刻表失败: ' + error.message);
        });
}

/**
 * 显示发车时刻表
 */
function displayBusSchedule(scheduleData, busName, direction = 'forward') {
    // 在公交线路搜索结果区域显示时刻表信息
    const resultsContainer = document.getElementById('bus-search-results');
    
    // 根据方向显示不同的标记
    const directionLabel = direction === 'reverse' ? 
        '<span class="badge bg-info">返程</span>' : 
        '<span class="badge bg-primary">去程</span>';
    
    // 创建时刻表提示框，但不覆盖现有内容
    let scheduleAlert = document.createElement('div');
    scheduleAlert.className = 'alert alert-info alert-dismissible fade show';
    scheduleAlert.setAttribute('role', 'alert');
    scheduleAlert.innerHTML = `
        <h5>${busName}路 ${directionLabel} 发车时刻表</h5>
        <div>${scheduleData || '暂无发车时刻表信息'}</div>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    // 插入到结果容器的最前面，而不是替换内容
    resultsContainer.insertBefore(scheduleAlert, resultsContainer.firstChild);
}

/**
 * 搜索地点（用于换乘路线规划）
 */
function searchLocation(type) {
    // 获取选中的城市名称
    const cityInput = document.getElementById('transfer-city-input');
    const cityName = cityInput.value;
    const keywords = document.getElementById(`${type}-location`).value;
    
    if (!cityName || !keywords) {
        showError('请选择城市并输入地点关键词');
        return;
    }
    
    showLoading('正在搜索地点...');
    
    fetch(`/api/search_location?city_name=${encodeURIComponent(cityName)}&keywords=${encodeURIComponent(keywords)}`)
        .then(response => response.json())
        .then(data => {
            hideLoading();
            
            if (data.return_code === 'ok') {
                const locations = data.returl_list || [];
                displayLocationResults(locations, type);
            } else {
                showError('搜索地点失败: ' + (data.error_code || '未知错误'));
            }
        })
        .catch(error => {
            hideLoading();
            showError('搜索地点失败: ' + error.message);
        });
}

/**
 * 显示地点搜索结果
 */
function displayLocationResults(locations, type) {
    const resultsContainer = document.getElementById(`${type}-location-results`);
    
    if (locations.length === 0) {
        resultsContainer.innerHTML = '<div class="alert alert-warning">未找到匹配的地点</div>';
        return;
    }
    
    let html = '<div class="list-group">';
    
    locations.forEach(location => {
        html += `
            <div class="location-item list-group-item list-group-item-action" 
                 data-name="${location.xyname}" 
                 data-imlgn="${location.imlgn}">
                <div>${location.xyname}</div>
                <small class="text-muted">${location.xyaddress}</small>
            </div>
        `;
    });
    
    html += '</div>';
    resultsContainer.innerHTML = html;
    
    // 绑定事件处理程序
    document.querySelectorAll(`#${type}-location-results .location-item`).forEach(item => {
        item.addEventListener('click', function() {
            // 设置选中样式
            document.querySelectorAll(`#${type}-location-results .location-item`).forEach(el => {
                el.classList.remove('selected');
            });
            this.classList.add('selected');
            
            // 设置表单值
            document.getElementById(`${type}-location`).value = this.dataset.name;
            document.getElementById(`${type}-imlgn`).value = this.dataset.imlgn;
        });
    });
}

/**
 * 规划换乘路线
 */
function planRoute(event) {
    event.preventDefault();
    
    const startStation = document.getElementById('start-location').value;
    const startImlgn = document.getElementById('start-imlgn').value;
    const endStation = document.getElementById('end-location').value;
    const endImlgn = document.getElementById('end-imlgn').value;
    
    if (!startStation || !startImlgn || !endStation || !endImlgn) {
        showError('请选择完整的起点和终点信息');
        return;
    }
    
    showLoading('正在规划换乘路线...');
    
    fetch(`/api/plan_route?start_station=${encodeURIComponent(startStation)}&start_imlgn=${encodeURIComponent(startImlgn)}&end_station=${encodeURIComponent(endStation)}&end_imlgn=${encodeURIComponent(endImlgn)}`)
        .then(response => response.json())
        .then(data => {
            hideLoading();
            
            if (data.return_code === 'ok') {
                displayRouteResults(data);
            } else {
                showError('规划换乘路线失败: ' + (data.error_code || '未知错误'));
            }
        })
        .catch(error => {
            hideLoading();
            showError('规划换乘路线失败: ' + error.message);
        });
}

/**
 * 显示换乘路线规划结果
 */
function displayRouteResults(data) {
    const resultsContainer = document.getElementById('transfer-results');
    
    if (!data.returl_list || data.returl_list.length === 0) {
        resultsContainer.innerHTML = '<div class="alert alert-warning">未找到可行的换乘路线</div>';
        return;
    }
    
    let html = `
        <h4>从 ${data.sta_station} 到 ${data.end_station} 的换乘方案</h4>
    `;
    
    data.returl_list.forEach((route, index) => {
        html += `
            <div class="transfer-route">
                <div class="transfer-route-header">方案 ${index + 1}</div>
                <div class="row mb-2">
                    <div class="col-md-4">
                        <strong>全程距离:</strong> ${route.xcdist || '未知'}
                    </div>
                    <div class="col-md-4">
                        <strong>预计时间:</strong> ${route.xydurtime || '未知'}
                    </div>
                    <div class="col-md-4">
                        <strong>步行距离:</strong> ${route.xywalkdist || '未知'}
                    </div>
                </div>
                <div class="mb-2">
                    <strong>票价:</strong> ${route.xcprice || '未知'}
                </div>
                <div class="route-details">
                    <ol class="list-group list-group-numbered">
        `;
        
        if (route.xytitle && route.xytitle.length > 0) {
            route.xytitle.forEach(step => {
                html += `<li class="list-group-item">${step}</li>`;
            });
        }
        
        html += `
                    </ol>
                </div>
            </div>
        `;
    });
    
    resultsContainer.innerHTML = html;
}

/**
 * 显示加载中提示
 */
function showLoading(message = '加载中...') {
    // 检查是否已存在loading元素
    let loadingEl = document.getElementById('loading-indicator');
    
    if (!loadingEl) {
        loadingEl = document.createElement('div');
        loadingEl.id = 'loading-indicator';
        loadingEl.className = 'loading';
        document.body.appendChild(loadingEl);
    }
    
    loadingEl.innerHTML = `
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <div class="mt-2">${message}</div>
    `;
    
    loadingEl.style.display = 'block';
}

/**
 * 隐藏加载中提示
 */
function hideLoading() {
    const loadingEl = document.getElementById('loading-indicator');
    if (loadingEl) {
        loadingEl.style.display = 'none';
    }
}

/**
 * 显示错误信息
 */
function showError(message) {
    const errorToast = new bootstrap.Toast(document.getElementById('error-toast') || createErrorToast());
    document.getElementById('error-message').textContent = message;
    errorToast.show();
}

/**
 * 创建错误提示框
 */
function createErrorToast() {
    const toastContainer = document.createElement('div');
    toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
    toastContainer.innerHTML = `
        <div id="error-toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header bg-danger text-white">
                <strong class="me-auto">错误</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body" id="error-message">
            </div>
        </div>
    `;
    document.body.appendChild(toastContainer);
    return document.getElementById('error-toast');
} 